<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: kane <chengjin005@163.com>
// +----------------------------------------------------------------------
namespace app\admin\controller\api;
use app\CommonController;
use app\plugins\ueditor\Ueditor as Uploader;

class Ueditor extends CommonController {

    public $config = array();
    /**
     * 初始化
     */
  public function initialize()
    {
        $ueditorConfig =PLUGIN_PATH."/ueditor/config.json";
        $this->config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($ueditorConfig)),true);
    }

    /**
     * 处理上传处理
     */
    public function upload()
    {

        $action = $this->request->param('action');
        $base64 = "upload";
        switch ($action) {
            case 'config':
                $result = json_encode($this->config);
                break;
            /* 上传图片 */
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $this->config['imagePathFormat'],
                    "maxSize" => $this->config['imageMaxSize'],
                    "allowFiles" => $this->config['imageAllowFiles']
                );
                $fieldName = $this->config['imageFieldName'];
                $result = $this->ueditorUpload($fieldName, $config, $base64);
                break;
            /* 上传涂鸦 */
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $this->config['scrawlPathFormat'],
                    "maxSize" => $this->config['scrawlMaxSize'],
                    "allowFiles" => $this->config['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $this->config['scrawlFieldName'];
                $base64 = "base64";
                $result = $this->ueditorUpload($fieldName, $config, $base64);
                break;
            /* 上传视频 */
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $this->config['videoPathFormat'],
                    "maxSize" => $this->config['videoMaxSize'],
                    "allowFiles" => $this->config['videoAllowFiles']
                );
                $fieldName = $this->config['videoFieldName'];
                $result = $this->ueditorUpload($fieldName, $config, $base64);
                break;
            /* 上传文件 */
            case 'uploadfile':
                $config = array(
                    "pathFormat" => $this->config['filePathFormat'],
                    "maxSize" => $this->config['fileMaxSize'],
                    "allowFiles" => $this->config['fileAllowFiles']
                );
                $fieldName = $this->config['fileFieldName'];
                $result = $this->ueditorUpload($fieldName, $config, $base64);
                 break;
            /* 列出图片 */
            case 'listimage':
                $result = "";
                break;
            /* 列出文件 */
            case 'listfile':
                $result = "";
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->_get_remote_image();
                break;

            default:
                $result = json_encode(['state' => '请求地址出错']);
                break;
        }
        if (!empty($this->request->param("callback"))) {
            if (preg_match("/^[\w_]+$/",$this->request->param("callback"))) {
                return htmlspecialchars($this->request->param("callback")) . '(' . $result . ')';
            } else {
                return json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
           echo $result;
           exit;
        }
    }

    /**
     * 获取远程图片
     */
    private function _get_remote_image()
    {

        $config = array(
            "pathFormat" => $this->config['catcherPathFormat'],
            "maxSize" => $this->config['catcherMaxSize'],
            "allowFiles" => $this->config['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName =$this->config['catcherFieldName'];
        /* 抓取远程图片 */
        $list = array();
        if (!empty($this->request->post($fieldName))) {
            $source = $this->request->post($fieldName);
        } else {
            $source = $this->request->param($fieldName);
        }
        foreach ($source as $imgUrl) {
            $item = new Uploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }

        /* 返回抓取数据 */
        return json_encode(array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        ));
    }

    /**
     * 文件上传
     * @param string $fileType 文件类型
     * @return string
     */
    private function ueditorUpload($fieldName, $config, $base64)
    {
        $up = new Uploader($fieldName, $config, $base64);
        return json_encode($up->getFileInfo());
    }


    /**
     * 格式化后缀
     * @param $str
     * @return string
     */
    private function ueditorExtension($str)
    {
        return "." . trim($str, '.');
    }

}
